package com.hn.kiss.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hn.kiss.config.common.CommonPage;
import com.hn.kiss.config.common.CommonResult;
import com.hn.kiss.config.common.MyException;
import com.hn.kiss.config.common.ParmException;
import com.hn.kiss.config.compoent.BaseController;
import com.hn.kiss.config.query.QueryGenerator;
import com.hn.kiss.config.util.UpLoadUtil;
import com.hn.kiss.config.validdator.FlagValidator;
import com.hn.kiss.modules.sys.dto.UserBaseDTO;
import com.hn.kiss.modules.sys.entity.User;
import com.hn.kiss.modules.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.IOException;


@Api(tags = "SysUserController", description = "用户管理")
@RestController
@RequestMapping("/sys/user")
@Validated
public class UserController extends BaseController {


    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IUserService userService;



    @ApiOperation("用户分页列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNo", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "pageSize", value = "每页数量", required = true, dataType = "Integer", paramType = "query"),
    })
    @GetMapping("/pageInfo")
    public CommonPage<User> pageInfo(@NotNull Integer pageNo,
                                     @NotNull Integer pageSize,
                                     User user,
                                     HttpServletRequest request){
        Page<User> pageInfo = new Page<>(pageNo, pageSize);
        //构造查询条件
        QueryWrapper<User> qw = QueryGenerator.initQueryWrapper(user, request.getParameterMap());
        Page<User> page1 = userService.page(pageInfo, qw);
        return CommonPage.restPage(page1);
    }

    @ApiOperation("通过主键获取用户")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "path")
    })
    @GetMapping("/{id}")
    public CommonResult<User> getByPk(@NotBlank@PathVariable("id") String id){
        User user = userService.getByPk(id);
        return CommonResult.success(user);
    }

    @ApiOperation("新增用户")
    @PostMapping
    public CommonResult add(@Validated User user, BindingResult bindingResult) throws ParmException {
        boolean b = userService.add(user);
        if (b)
            return CommonResult.success("成功");

        return CommonResult.failed("失败");
    }

    @ApiOperation("修改用户基础信息")
    @PutMapping("/base")
    public CommonResult base(@Validated UserBaseDTO userBaseDTO, BindingResult bindingResult){
        User user = userBaseDTO.convertToUser();
        boolean b = userService.updateByPk(user);
        if (b){
            return CommonResult.success("成功");
        }
        return CommonResult.failed("失败");
    }

    @ApiOperation("修改用户密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "oldpwd", value = "旧密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "newpwd", value = "新密码", required = true, dataType = "String", paramType = "query")
    })
    @PatchMapping("/password")
    public CommonResult password(@NotBlank String id, @NotBlank String oldpwd, @NotBlank@Size(min = 6, max = 20) String newpwd) throws MyException {
        boolean b = userService.updatePwd(id, oldpwd, newpwd);
        if (b){
            return CommonResult.success("成功");
        }
        return CommonResult.failed("失败");

    }


    @ApiOperation("修改用户手机号,身份证号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "idno", value = "身份证号", required = true, dataType = "String", paramType = "query")
    })
    @PatchMapping("/phoneOrIdno")
    public CommonResult updateBase(@NotBlank String id, String phone, String idno) throws MyException, ParmException {
        boolean isEmpty = StringUtils.isEmpty(phone) && StringUtils.isEmpty(idno);
        if (isEmpty)
            return CommonResult.failed();
        //校验重复
        userService.checkUser(phone, null, idno);

        LambdaUpdateWrapper<User> updateWrapper = new UpdateWrapper<User>().lambda()
                .set(User::getPhone, phone)
                .set(User::getIdno, idno)
                .eq(User::getId, id);
        boolean b = userService.update(updateWrapper);
        if (b){
            return CommonResult.success("成功");
        }
        return CommonResult.failed("失败");

    }



    @ApiOperation("通过主键删除用户")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public CommonResult removeByPk(@NotBlank@PathVariable("id") String id){
        boolean b = userService.removeByPk(id);
        if (b){
            return CommonResult.success("成功");
        }
        return CommonResult.failed("失败");
    }


    @ApiOperation("用户停启用")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "state", value = "状态码(1启用,2停用)", required = true, dataType = "String", paramType = "query")
    })
    @PatchMapping("/state")
    public CommonResult updatestate(@NotBlank String id, @NotBlank @FlagValidator(value = {"1", "2"}) String state){
        LambdaUpdateWrapper<User> updateWrapper = new UpdateWrapper<User>().lambda()
                .set(User::getState, state)
                .eq(User::getId, id);
        boolean b = userService.update(updateWrapper);
        if (b){
            return CommonResult.success("成功");
        }
        return CommonResult.failed("失败");
    }




    @ApiOperation("用户头像上传")
    @PostMapping(value="/headImgUpload",consumes="multipart/*", headers="content-type=multipart/form-data")
    public CommonResult headImgUpload(@RequestParam("file") MultipartFile file) throws IOException {
        String path = UpLoadUtil.uploadBeltDate(file, "user/headImg");
        return CommonResult.success(path);
    }




}
